package com.cn.wanxi.dao.impl;

import com.cn.wanxi.dao.ProductDao;
import com.cn.wanxi.model.ProdudctModel;
import com.cn.wanxi.util.JDBC;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ProductImpl implements ProductDao {
    @Override
    public int add(ProdudctModel produdctModel) {
        String sql = "INSERT INTO `product` (" +
                "`name`, " +
                "`normal_price`," +
                " `price`, " +
                "`content`, " +
                "`is_show`, " +
                "`is_recommend`," +
                " `img_href`, " +
                "`cuisine_id`, " +
                "`create_time`," +
                " `update_time`," +
                " `enable`) VALUES (" +
                "'" + produdctModel.getProductName() + "'," +
                " '" + produdctModel.getNormalPrice() + "', " +
                "'" + produdctModel.getMarketPrice() + "', " +
                "'" + produdctModel.getContent() + "', '1', '1', " +
                "'" + produdctModel.getImgHref() + "'," +
                " '" + produdctModel.getCusineId() + "'," +
                " now(),now(), '1');";
        return JDBC.update(sql);
    }

    @Override
    public List<ProdudctModel> findAll() {
        String sql = "select * from product";
        return setData(sql);
    }

    @Override
    public ProdudctModel findById(int id) {
        String sql = "select * from product where id=" + id;

        return setData(sql).get(0);
    }

    private List<ProdudctModel> setData(String sql) {
        ResultSet resultSet = JDBC.query(sql);
        List<ProdudctModel> list = new ArrayList<>();
        try {
            while (resultSet.next()) {
                ProdudctModel model = new ProdudctModel();
                model.setId(resultSet.getInt("id"));
                model.setProductName(resultSet.getString("name"));
                model.setMarketPrice(resultSet.getFloat("price"));
                model.setNormalPrice(resultSet.getFloat("normal_price"));
                model.setContent(resultSet.getString("content"));
                model.setImgHref(resultSet.getString("img_href"));
                model.setCusineId(resultSet.getInt("cuisine_id"));
                model.setEnable(resultSet.getInt("enable"));
                list.add(model);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}

